/**
 * 
 */
package vn.com.demand.lux.view;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Blank;
import jxl.write.DateFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CellNavigationStrategy;
import org.eclipse.jface.viewers.ColumnViewer;
import org.eclipse.jface.viewers.ColumnViewerEditor;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationEvent;
import org.eclipse.jface.viewers.ColumnViewerEditorActivationStrategy;
import org.eclipse.jface.viewers.FocusCellOwnerDrawHighlighter;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.TableViewerEditor;
import org.eclipse.jface.viewers.TableViewerFocusCellManager;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.viewers.ViewerRow;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.nebula.widgets.formattedtext.FormattedText;
import org.eclipse.nebula.widgets.formattedtext.TimeFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.EditorPart;

import vn.com.demand.lux.Activator;
import vn.com.demand.lux.criteria.ServiceCardCriteria;
import vn.com.demand.lux.editor.DateCellEditor;
import vn.com.demand.lux.model.ServiceCardBean;
import vn.com.demand.lux.model.ServiceCardManager;
import vn.com.demand.lux.modifier.ServiceCardCellModifier;
import vn.com.demand.lux.view.labelprovider.ServiceCardLabelProvider;
import vn.com.demand.util.DpUtils;
import vn.com.demand.widget.SelectItemCodeHeader;
import vn.com.demand.widget.SearcheableTable.MyModel;

import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @author Nguyen The Thinh
 *
 */
public class CopyOfServiceCardEditor extends EditorPart implements FocusListener {

	private Button browseButton;
	private Table table;
	private Text customerCode;
	private Text contract;
	private Text serviceCard;
	private Text resource;
	private DateChooserCombo toDate;
	private DateChooserCombo fromDate;
	private TableViewer tableViewer;
	private TableViewerFocusCellManager focusCellManager;
	private CellEditor[] editors;
	public static final String ID = "vn.com.demand.lux.view.ServiceCardEditor"; //$NON-NLS-1$
	private String[] columnHeaders = new String[] {"Card number", "Resource ID", "Date", "From", "To", "Customer code", "Customer name",
			"Contract number", "Service detail", "Type"};
	private List<ServiceCardBean> inputList;
	private ArrayList<ServiceCardBean> updateList = new ArrayList<ServiceCardBean>();
	private FormattedText fromTextFormat;
	private FormattedText toTextFormat;
	private ServiceCardCriteria criteria;
	/**
	 * Create contents of the editor part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		FormToolkit toolkit = new FormToolkit(Display.getCurrent());
		Composite container = toolkit.createComposite(parent, SWT.NONE);
		container.setLayout(new FillLayout());

		final Form serviceCardForm = toolkit.createForm(container);
		final Composite body = serviceCardForm.getBody();
		body.setLayout(new FormLayout());
		toolkit.paintBordersFor(body);

		final Section generalInformationSection = toolkit.createSection(body, Section.TITLE_BAR | Section.FOCUS_TITLE);
		final FormData fd_generalInformationSection = new FormData();
		fd_generalInformationSection.top = new FormAttachment(0, 5);
		fd_generalInformationSection.right = new FormAttachment(100, -5);
		fd_generalInformationSection.left = new FormAttachment(0, 5);
		generalInformationSection.setLayoutData(fd_generalInformationSection);
		generalInformationSection.setText("General Information");

		final Composite composite = toolkit.createComposite(generalInformationSection, SWT.NONE);
		composite.setLayout(new FormLayout());
		generalInformationSection.setClient(composite);
		toolkit.paintBordersFor(composite);

		final Label fromDateLabel = toolkit.createLabel(composite, "From date", SWT.NONE);
		fromDateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		final FormData fd_fromDateLabel = new FormData();
		fd_fromDateLabel.bottom = new FormAttachment(0, 24);
		fd_fromDateLabel.top = new FormAttachment(0, 11);
		fd_fromDateLabel.left = new FormAttachment(0, 10);
		fromDateLabel.setLayoutData(fd_fromDateLabel);

		fromDate = new DateChooserCombo(composite, SWT.BORDER);
		final FormData fd_text = new FormData();
		fd_text.top = new FormAttachment(0, 11);
		fd_text.bottom = new FormAttachment(0, 30);
		fd_text.right = new FormAttachment(0, 185);
		fd_text.left = new FormAttachment(0, 90);
		fromDate.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));
		fromDate.setLayoutData(fd_text);

		final Label fromDateLabel_1 = toolkit.createLabel(composite, "To date", SWT.NONE);
		final FormData fd_fromDateLabel_1 = new FormData();
		fd_fromDateLabel_1.right = new FormAttachment(0, 59);
		fd_fromDateLabel_1.left = new FormAttachment(0, 10);
		fd_fromDateLabel_1.top = new FormAttachment(0, 41);
		fd_fromDateLabel_1.bottom = new FormAttachment(0, 54);
		fromDateLabel_1.setLayoutData(fd_fromDateLabel_1);
		fromDateLabel_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		toDate = new DateChooserCombo(composite, SWT.BORDER);
		final FormData fd_toDate = new FormData();
		fd_toDate.top = new FormAttachment(0, 41);
		fd_toDate.right = new FormAttachment(0, 185);
		fd_toDate.left = new FormAttachment(0, 90);
		fd_toDate.bottom = new FormAttachment(0, 60);
		toDate.setFormatter(new DateFormatter(Activator.getDefault().getDateFormatTypePreferences()));
		toDate.setLayoutData(fd_toDate);
		toolkit.adapt(toDate);

		final Label fromDateLabel_2 = toolkit.createLabel(composite, "Resource", SWT.NONE);
		final FormData fd_fromDateLabel_2 = new FormData();
		fd_fromDateLabel_2.top = new FormAttachment(0, 11);
		fd_fromDateLabel_2.bottom = new FormAttachment(0, 24);
		fd_fromDateLabel_2.right = new FormAttachment(0, 315);
		fd_fromDateLabel_2.left = new FormAttachment(0, 255);
		fromDateLabel_2.setLayoutData(fd_fromDateLabel_2);
		fromDateLabel_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		resource = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_resource = new FormData();
		fd_resource.top = new FormAttachment(0, 11);
		fd_resource.left = new FormAttachment(0, 325);
		fd_resource.bottom = new FormAttachment(0, 30);
		fd_resource.right = new FormAttachment(0, 460);
		resource.setLayoutData(fd_resource);

		final Label fromDateLabel_2_1 = toolkit.createLabel(composite, "Service card", SWT.NONE);
		final FormData fd_fromDateLabel_2_1 = new FormData();
		fd_fromDateLabel_2_1.top = new FormAttachment(0, 41);
		fd_fromDateLabel_2_1.bottom = new FormAttachment(0, 54);
		fd_fromDateLabel_2_1.left = new FormAttachment(0, 255);
		fd_fromDateLabel_2_1.right = new FormAttachment(0, 315);
		fromDateLabel_2_1.setLayoutData(fd_fromDateLabel_2_1);
		fromDateLabel_2_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		serviceCard = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_serviceCard = new FormData();
		fd_serviceCard.top = new FormAttachment(0, 41);
		fd_serviceCard.right = new FormAttachment(0, 460);
		fd_serviceCard.left = new FormAttachment(0, 325);
		fd_serviceCard.bottom = new FormAttachment(0, 60);
		serviceCard.setLayoutData(fd_serviceCard);

		final Label fromDateLabel_2_2 = toolkit.createLabel(composite, "Contract", SWT.NONE);
		final FormData fd_fromDateLabel_2_2 = new FormData();
		fd_fromDateLabel_2_2.left = new FormAttachment(0, 515);
		fd_fromDateLabel_2_2.top = new FormAttachment(0, 11);
		fd_fromDateLabel_2_2.bottom = new FormAttachment(0, 24);
		fd_fromDateLabel_2_2.right = new FormAttachment(0, 575);
		fromDateLabel_2_2.setLayoutData(fd_fromDateLabel_2_2);
		fromDateLabel_2_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_2.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		contract = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_contract = new FormData();
		fd_contract.right = new FormAttachment(0, 730);
		fd_contract.left = new FormAttachment(0, 595);
		fd_contract.bottom = new FormAttachment(0, 30);
		fd_contract.top = new FormAttachment(0, 11);
		contract.setLayoutData(fd_contract);

		Label fromDateLabel_2_1_1;
		fromDateLabel_2_1_1 = toolkit.createLabel(composite, "Customer code", SWT.NONE);
		final FormData fd_fromDateLabel_2_1_1 = new FormData();
		fd_fromDateLabel_2_1_1.right = new FormAttachment(0, 595);
		fd_fromDateLabel_2_1_1.left = new FormAttachment(0, 515);
		fd_fromDateLabel_2_1_1.bottom = new FormAttachment(0, 54);
		fd_fromDateLabel_2_1_1.top = new FormAttachment(0, 41);
		fromDateLabel_2_1_1.setLayoutData(fd_fromDateLabel_2_1_1);
		fromDateLabel_2_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		customerCode = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_customerCode = new FormData();
		fd_customerCode.left = new FormAttachment(0, 595);
		fd_customerCode.right = new FormAttachment(0, 730);
		fd_customerCode.bottom = new FormAttachment(0, 60);
		fd_customerCode.top = new FormAttachment(0, 41);
		customerCode.setLayoutData(fd_customerCode);

		final Button clearButton = toolkit.createButton(composite, "Clear", SWT.NONE);
		clearButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doClear();
			}
		});
		clearButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/eraser.png"));
		final FormData fd_clearButton = new FormData();
		fd_clearButton.bottom = new FormAttachment(contract, 0, SWT.BOTTOM);
		fd_clearButton.right = new FormAttachment(0, 830);
		fd_clearButton.top = new FormAttachment(0, 11);
		fd_clearButton.left = new FormAttachment(0, 770);
		clearButton.setLayoutData(fd_clearButton);

		final Section detailSection = toolkit.createSection(body, Section.TITLE_BAR | Section.FOCUS_TITLE);
		final FormData fd_detailSection = new FormData();
		fd_detailSection.top = new FormAttachment(0, 130);
		fd_detailSection.left = new FormAttachment(0, 5);
		fd_detailSection.right = new FormAttachment(100, -5);
		detailSection.setLayoutData(fd_detailSection);
		detailSection.setText("Detail");

		final Composite detailComposite = toolkit.createComposite(detailSection, SWT.NONE);
		detailComposite.setLayout(new FillLayout());
		detailSection.setClient(detailComposite);
		toolkit.paintBordersFor(detailComposite);
		
		createTableViewerEditor(detailComposite);

		Composite buttonBar;
		buttonBar = toolkit.createComposite(body, SWT.NONE);
		fd_detailSection.bottom = new FormAttachment(buttonBar, -5, SWT.TOP);
		buttonBar.setLayout(new FillLayout());
		final FormData fd_buttonBar = new FormData();
		fd_buttonBar.top = new FormAttachment(100, -27);
		fd_buttonBar.left = new FormAttachment(100, -268);
		fd_buttonBar.right = new FormAttachment(100, -5);
		fd_buttonBar.bottom = new FormAttachment(100, -5);
		buttonBar.setLayoutData(fd_buttonBar);
		toolkit.paintBordersFor(buttonBar);
		
		final Button button = toolkit.createButton(buttonBar, "&Refresh", SWT.NONE);
		button.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/reload.png"));
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSearch();
			}
		});

		final Button button_1 = toolkit.createButton(buttonBar, "&Save", SWT.NONE);
		button_1.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/save_all.png"));
		button_1.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doSave(null);
			}
		});

		final Button button_3 = toolkit.createButton(buttonBar, "E&xport", SWT.NONE);
		button_3.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport();
			}
		});
		button_3.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/excel.gif"));

		final Button button_2 = toolkit.createButton(buttonBar, "Clos&e", SWT.NONE);
		button_2.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/shutdown.png"));
		button_2.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doClose();
			}
		});

		Composite buttonHeaderBar;
		buttonHeaderBar = toolkit.createComposite(body, SWT.NONE);
		fd_generalInformationSection.bottom = new FormAttachment(buttonHeaderBar, 0, SWT.TOP);
		buttonHeaderBar.setLayout(new FillLayout());
		final FormData fd_buttonHeaderBar = new FormData();
		fd_buttonHeaderBar.right = new FormAttachment(0, 195);
		fd_buttonHeaderBar.top = new FormAttachment(0, 110);
		fd_buttonHeaderBar.left = new FormAttachment(detailSection, 0, SWT.LEFT);
		fd_buttonHeaderBar.bottom = new FormAttachment(detailSection, 0, SWT.TOP);
		buttonHeaderBar.setLayoutData(fd_buttonHeaderBar);
		toolkit.paintBordersFor(buttonHeaderBar);

		final Button button_5 = toolkit.createButton(buttonHeaderBar, "&Insert", SWT.NONE);
		button_5.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doInsert();
			}
		});
		button_5.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/inserttable.png"));

		final Button button_4 = toolkit.createButton(buttonHeaderBar, "&Delete", SWT.NONE);
		button_4.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doDelete();
			}
		});
		button_4.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/14_layer_deletelayer.png"));

		browseButton = toolkit.createButton(buttonHeaderBar, "&Browse", SWT.NONE);
		browseButton.setEnabled(false);
		browseButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doBrowse();
			}
		});
		browseButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/viewmag+.png"));

		serviceCardForm.setText("Service Card");
	}

	
	protected void doInsert() {
		int rowIndex = tableViewer.getTable().getSelectionIndex();
		ServiceCardBean addedBean = new ServiceCardBean();
		if (rowIndex > -1) {
			inputList.add(rowIndex, addedBean);

		} else {
			inputList.add(inputList.size(), addedBean);
		}
		updateList.add(addedBean);
		tableViewer.setInput(inputList);
	}


	protected void doDelete() {
		ServiceCardBean element = (ServiceCardBean) ((StructuredSelection)tableViewer.getSelection()).getFirstElement();
		if (null != element) {
			if (MessageDialog.openConfirm(null, "Confirm", "Do you really want to delete?")) {
				try {
					if (element.getId() > 0) {
						element.delete();
					} 
					inputList.remove(element);
					tableViewer.setInput(inputList);
				} catch (SQLException e) {
					e.printStackTrace();
					MessageDialog.openError(null, "Error", e.getMessage());
				}
			}
		} 
	}


	protected void doClear() {
		fromDate.setValue(null);
		toDate.setValue(null);
		resource.setText("");
		serviceCard.setText("");
		contract.setText("");
		customerCode.setText("");
		doSearch();
	}


	protected void doExport() {
		FileDialog fileDialog = new FileDialog(this.getEditorSite().getShell(), SWT.SAVE);
		fileDialog.setFilterExtensions(new String[] { "*.xls" });
		fileDialog.setFilterNames(new String[] { "Excel files" });
		String reportLocation = fileDialog.open();
		if (null != reportLocation) {
			File file = new File(reportLocation);
			WritableWorkbook resultBook;
			try {
				int beginCol = 0;
				resultBook = Workbook.createWorkbook(file);
				WritableSheet resultSheet = resultBook.createSheet(
						"Result", 0);
				int beginRow = setReportHeader(resultSheet, 0);
				// remove rows before rewrite
				for (int i = beginRow; i < resultSheet.getRows(); i++) {
					resultSheet.removeRow(i);
				}
				
				DateFormat format = new DateFormat(Activator.getDefault()					
						.getDateFormatTypePreferences());
				WritableCellFormat dateFormat = new WritableCellFormat(format);
				
				//other font
				WritableFont defaultFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
				defaultFont.setColour(Colour.BLACK);
				
				if (null != resultSheet) {
					for (ServiceCardBean card : inputList) {
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getCardNumber()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getResourceId()));
						if (null != card.getDate() ) {
							resultSheet.addCell(new jxl.write.DateTime(beginCol++, beginRow, card.getDate(), dateFormat));
						} else {
							resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, ""));
						}
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getFromTime()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getToTime()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getCustomerCode()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getCustomerName()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getContractNumber()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow, card.getServiceDetail()));
						resultSheet.addCell(new jxl.write.Label(beginCol++, beginRow++, card.getType()));
						beginCol = 0;
					}
				}
				resultBook.write();
				resultBook.close();
				MessageBox box = new MessageBox(this.getEditorSite().getShell(), SWT.OK | SWT.CANCEL
						| SWT.ICON_INFORMATION);
				box
						.setMessage("Export completed, click OK to open the result file now or click cancel to open it manually later");
				int i = box.open();
				if (i == SWT.OK) {
					Runtime.getRuntime().exec(
							"cmd.exe /C \"" + reportLocation + "\"");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (RowsExceededException e) {
				e.printStackTrace();
			} catch (WriteException e) {
				e.printStackTrace();
			}
		}
}


	private int setReportHeader(WritableSheet resultSheet, int i) {
		WritableCellFormat tf;
//		WritableCellFormat numberFormat = new WritableCellFormat(
//				NumberFormats.FLOAT);
		try {
			WritableFont title = new WritableFont(WritableFont.ARIAL, 20,
					WritableFont.BOLD);
			title.setColour(Colour.BLACK);
			tf = new WritableCellFormat(title);
			tf.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, i, "Service Card", tf));
			resultSheet.mergeCells(0, i, 1, i++);
			WritableFont criteriaFont = new WritableFont(WritableFont.ARIAL,
					10, WritableFont.BOLD);
			criteriaFont.setColour(Colour.BLUE);
			WritableCellFormat criteriaFormat = new WritableCellFormat(
					criteriaFont);
			// add an empty row
			i++;
			// Criteria
			WritableFont font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
			WritableCellFormat boldFormat = new WritableCellFormat(font);
			boldFormat.setAlignment(Alignment.LEFT);
			
			WritableFont alinRightFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
			WritableCellFormat alignRightCellFormat = new WritableCellFormat(alinRightFont);
			alignRightCellFormat.setAlignment(Alignment.RIGHT);
			
			resultSheet.addCell(new jxl.write.Label(0, i++, "General Information", boldFormat));
//			resultSheet.mergeCells(0, i, 3, i);
			
			DateFormat format = new DateFormat(Activator.getDefault()
					.getDateFormatTypePreferences());
			WritableCellFormat dateFormat = new WritableCellFormat(format);
			//1st header row
			resultSheet.addCell(new jxl.write.Label(0, i, "From date",
					criteriaFormat));
			if (null != fromDate.getValue()) {
				resultSheet.addCell(new jxl.write.DateTime(1, i, fromDate.getValue() , dateFormat));
			} else {
				resultSheet.addCell(new Blank(1, i));
			}
			resultSheet.addCell(new jxl.write.Label(2, i, "Resource",criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, i, resource.getText()));
			resultSheet.addCell(new jxl.write.Label(4, i, "Contract", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i++, contract.getText()));
			
			//2nd header row
			resultSheet.addCell(new jxl.write.Label(0, i, "To date", criteriaFormat));
			if (null != toDate.getValue()) {
				resultSheet.addCell(new jxl.write.DateTime(1, i, toDate.getValue(), dateFormat));
			} else {
				resultSheet.addCell(new Blank(1, i));
			}
			resultSheet.addCell(new jxl.write.Label(2, i, "Serviec card", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, i, serviceCard.getText()));
			resultSheet.addCell(new jxl.write.Label(4, i, "Customer code",criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i++, customerCode.getText()));

			//Detail row header
			WritableFont underLineFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, true, UnderlineStyle.SINGLE);
			WritableCellFormat undeLineFontCellFormat = new WritableCellFormat(underLineFont);
			undeLineFontCellFormat.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, i++,
					"Detail Information", undeLineFontCellFormat));

			// set font and background color
			WritableFont header = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			header.setColour(Colour.WHITE);
			WritableCellFormat hf = new WritableCellFormat(header);
			hf.setBackground(Colour.BLUE);
			hf.setAlignment(Alignment.CENTRE);
			hf.setVerticalAlignment(VerticalAlignment.CENTRE);
			hf.setWrap(true);
			int col = 0;
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Card number", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Resource ID", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Date", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "From", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "To", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Customer code", hf));
			resultSheet.setColumnView(col, 30);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Customer name", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Contract number", hf));
			resultSheet.setColumnView(col, 25);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Service detail", hf));
			resultSheet.setColumnView(col, 30);
			resultSheet.addCell(new jxl.write.Label(col, i++, "Type", hf));
			return i;
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return 0;
	}


	protected void doClose() {
		if (isDirty) {
			MessageDialog dlg = new MessageDialog(
					this.getEditorSite().getShell(),
					"Save and Exit",
					null,
					"Service cards has being edited. Do you want to save it before exit?",
					MessageDialog.QUESTION, new String[] { "Yes", "No",
							"Cancel" }, 0);
				switch (dlg.open()) {
				case 0:
					doSave(null);
					setDirty(false);
					this.getEditorSite().getWorkbenchWindow().getActivePage().closeEditor(this, false);
					break;
				case 1:
					this.getEditorSite().getWorkbenchWindow().getActivePage().closeEditor(this, false);
					break;
				default:
					return;
			}  
		} else {
			this.getEditorSite().getWorkbenchWindow().getActivePage().closeEditor(this, false);
		}
	}


	protected void doSearch() {
		if (null != fromDate.getValue()) {
			criteria.setFromDate(new java.sql.Date(fromDate.getValue().getTime()));
		} else {
			criteria.setFromDate(null);
		}
		if (null != toDate.getValue()) {
			criteria.setToDate(new java.sql.Date(toDate.getValue().getTime()));
		} else {
			criteria.setToDate(null);
		}
		criteria.setResourceId(resource.getText());
		criteria.setServiceCard(serviceCard.getText());
		criteria.setContractNumber(contract.getText());
		criteria.setCustomerCode(customerCode.getText());
		inputList = criteria.search();
		tableViewer.setInput(inputList);
	}


	protected void doSaveServiceCard() {
		if (null != updateList && !updateList.isEmpty()) {
			try {
				ServiceCardManager.saveServiceCards(updateList);
				MessageDialog.openInformation(null, "Saved", "Service cards were saved");
				updateList.clear();
//				tableViewer.setInput(inputList);
			} catch (SQLException e) {
				e.printStackTrace();
				MessageDialog.openError(null, "Error", e.getMessage());
			}
		}
	}


	private void createTableViewerEditor(Composite parent) {
		tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION);

		tableViewer.setUseHashlookup(true);
		table = tableViewer.getTable();

		for (int i = 0; i < columnHeaders.length; i++) {
			TableViewerColumn column = new TableViewerColumn(tableViewer,
					SWT.NONE);
			column.getColumn().setText(columnHeaders[i]);
			column.getColumn().setWidth(100);
		}

		FocusCellOwnerDrawHighlighter highlighter = new FocusCellOwnerDrawHighlighter(tableViewer);
		
		focusCellManager = new TableViewerFocusCellManager(tableViewer, highlighter);

		editors = new CellEditor[columnHeaders.length];

		// Create the cell editors
		TextCellEditor textEditor = new TextCellEditor(table);
		// Card number
		textEditor.getControl().addFocusListener(this);
		editors[0] = textEditor;

		// Resource ID
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addKeyListener(new KeyListener(){

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doBrowse();
				}
			}

			public void keyReleased(KeyEvent e) {
			}
			
		});
		textEditor.getControl().addFocusListener(this);
		textEditor.getControl().setToolTipText("Press F5 to select Resource ID");
		editors[1] = textEditor;

		// Date
		DateCellEditor dateEditor = new DateCellEditor(table);
		dateEditor.getControl().addFocusListener(this);
		editors[2] = dateEditor;
		
		//From
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addFocusListener(this);
		editors[3] = textEditor;
		fromTextFormat = new FormattedText((Text)editors[3].getControl());
		fromTextFormat.setFormatter(new TimeFormatter("hh:mm:a"));
		
		//To
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addFocusListener(this);
		editors[4] = textEditor;
		toTextFormat = new FormattedText((Text)editors[4].getControl());
		toTextFormat.setFormatter(new TimeFormatter("hh:mm:a"));
		
		//Customer code
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addKeyListener(new KeyListener(){

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doBrowse();
				}
			}

			public void keyReleased(KeyEvent e) {
			}
			
		});
		textEditor.getControl().setToolTipText("Press F5 to select Customer code");
		textEditor.getControl().addFocusListener(this);
		editors[5] = textEditor;
		
		//Customer name
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addFocusListener(this);
		editors[6] = textEditor;
		
		//Contract number
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addFocusListener(this);
		textEditor.getControl().addKeyListener(new KeyListener(){

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doBrowse();
				}
			}

			public void keyReleased(KeyEvent e) {
			}
			
		});
		textEditor.getControl().setToolTipText("Press F5 to select Contract number");
		editors[7] = textEditor;
		
		//Service detail
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addFocusListener(this);
		editors[8] = textEditor;
		
		//Type
		textEditor = new TextCellEditor(table);
		textEditor.getControl().addFocusListener(this);
		textEditor.getControl().addKeyListener(new KeyListener(){

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.F5) {
					doBrowse();
				}
			}

			public void keyReleased(KeyEvent e) {
			}
			
		});
		textEditor.getControl().setToolTipText("Press F5 to select Type");
		editors[9] = textEditor;
		
		tableViewer.setColumnProperties(columnHeaders);
		tableViewer.setCellEditors(editors);
//		tableViewer.setCellModifier(new ServiceCardCellModifier(this));
		
		ColumnViewerEditorActivationStrategy actSupport = new ColumnViewerEditorActivationStrategy(
				tableViewer) {
			protected boolean isEditorActivationEvent(
					ColumnViewerEditorActivationEvent event) {
				return event.eventType == ColumnViewerEditorActivationEvent.TRAVERSAL
						|| event.eventType == ColumnViewerEditorActivationEvent.MOUSE_DOUBLE_CLICK_SELECTION
						|| (event.eventType == ColumnViewerEditorActivationEvent.KEY_PRESSED && event.keyCode == SWT.CR)
						|| event.eventType == ColumnViewerEditorActivationEvent.PROGRAMMATIC;
			}
		};

		TableViewerEditor.create(tableViewer, focusCellManager, actSupport,
				ColumnViewerEditor.TABBING_HORIZONTAL
						| ColumnViewerEditor.TABBING_MOVE_TO_ROW_NEIGHBOR
						| ColumnViewerEditor.TABBING_VERTICAL
						| ColumnViewerEditor.KEYBOARD_ACTIVATION);
		tableViewer.setLabelProvider(new ServiceCardLabelProvider());
		tableViewer.setContentProvider(new ServiceCardContentProvider());
		tableViewer.getTable().setLinesVisible(true);
		tableViewer.getTable().setHeaderVisible(true);
		initData();
	}
	
	public TableViewer getTableViewer() {
		return tableViewer;
	}
	
	public void doBrowse() {
		int columnIndex = focusCellManager.getFocusCell().getColumnIndex();
		switch (columnIndex) {
		case 1:
			doSelectResourceId();
			break;
		case 5:
			doSelectCustomerCode();
			break;
		case 7:
			doSelectContractNumber();
			break;
		case 9:
			doSelectType();
			break;
		default:
			break;
		}
	}
	
	private void doSelectType() {
		SelectItemCodeHeader header = new SelectItemCodeHeader(
				Display.getCurrent().getActiveShell(),
				"select selcode as code, oms30_0 as description from demand_issuingpurpose order by code");
		if (header.open() == Dialog.OK) {
			ServiceCardBean element = (ServiceCardBean) focusCellManager
					.getFocusCell().getElement();
			MyModel item = (MyModel) header.getSelectedObject();
			if (null != item) {
				element.setType(item.getDescription());
//				setDirty(true);
			}
			tableViewer.refresh();
		}
		tableViewer.getTable().setFocus();
	}


	private void doSelectContractNumber() {
		ServiceCardBean element = (ServiceCardBean) focusCellManager
		.getFocusCell().getElement();
		String sql = "select contractnumber as code, contractdescription as description from demand_contractinformation";
		if (element != null && null != element.getCustomerCode() && element.getCustomerCode().length() > 0) {
			sql += " where rtrim(ltrim(customercode)) = '" + DpUtils.trim(element.getCustomerCode()) + "'";
		}
		sql += " order by code";
		SelectItemCodeHeader header = new SelectItemCodeHeader(
				Display.getCurrent().getActiveShell(), sql);
		System.out.println("SQL :" +sql);
		header.setCodeLabel("Contract number");
		header.setDescriptionLabel("Contract description");
		if (header.open() == Dialog.OK) {
			MyModel item = (MyModel) header.getSelectedObject();
			if (null != item) {
				element.setContractNumber(item.getCode());
//				setDirty(true);
			}
			tableViewer.refresh();
		}
		tableViewer.getTable().setFocus();
	}

	private void doSelectResourceId() {
		SelectItemCodeHeader header = new SelectItemCodeHeader(
				Display.getCurrent().getActiveShell(),
				"select res_id as code, fullname as description from demand_resourcelist order by code");
		header.setCodeLabel("Resource ID");
		header.setDescriptionLabel("Full Name");
		if (header.open() == Dialog.OK) {
			ServiceCardBean element = (ServiceCardBean) focusCellManager
					.getFocusCell().getElement();
			MyModel item = (MyModel) header.getSelectedObject();
			if (null != item) {
				element.setResourceId(item.getCode());
				setDirty(true);
			}
			tableViewer.refresh();
			tableViewer.getTable().setFocus();
		}
	}

	private void doSelectCustomerCode() {
		SelectItemCodeHeader header = new SelectItemCodeHeader(
				Display.getCurrent().getActiveShell(),
				"select cmp_code as code, cmp_name as description from demand_customerlist order by code");
		header.setCodeLabel("Customer code");
		header.setDescriptionLabel("Customer name");
		if (header.open() == Dialog.OK) {
			final ServiceCardBean element = (ServiceCardBean) focusCellManager
					.getFocusCell().getElement();
			MyModel item = (MyModel) header.getSelectedObject();
			if (null != item) {
				element.setCustomerCode(item.getCode());
				element.setCustomerName(item.getDescription());
			}
			tableViewer.refresh();
		}
		 tableViewer.getTable().setFocus();
	}

	public void initData() {
		setDirty(false);
		criteria = new ServiceCardCriteria();
		inputList = criteria.search();
		tableViewer.setInput(inputList);
	}
	
	public List<String> getColumnNames() {
		return Arrays.asList(columnHeaders);
	} 	
	
	private int doValidate(List<ServiceCardBean> list) {
		if (null != list && !list.isEmpty()) {
			for (ServiceCardBean bean : list) {
				if (null == bean.getCardNumber() || bean.getCardNumber().length() == 0) {
					return 0;
				}
				if (null == bean.getResourceId() || bean.getResourceId().length() == 0) {
					return 1;
				}
				if (null == bean.getDate()) {
					return 2;
				}
				if (null == bean.getCustomerCode() || bean.getCustomerCode().length() == 0) {
					return 5;
				}
				if (null == bean.getCustomerName() || bean.getCustomerName().length() == 0) {
					return 6;
				}
				if (null == bean.getContractNumber() || bean.getContractNumber().length() == 0) {
					return 7;
				}
				if (null == bean.getType() || bean.getType().length() == 0) {
					return 9;
				}
			}
		}
		return -1;
	}
	
	@Override
	public void setFocus() {
		// Set the focus
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// Do the Save operation
		switch (doValidate(updateList)) {
		case 0:
			MessageDialog.openError(null, "Error", "Card number can not be empty");
			return;
		case 1:
			MessageDialog.openError(null, "Error", "Resource can not be empty");
			return;
		case 2:	
			MessageDialog.openError(null, "Error", "Date can not be empty");
			return;	
		case 5:	
			MessageDialog.openError(null, "Error", "Customer code can not be empty");
			return;
		case 6:	
			MessageDialog.openError(null, "Error", "Customer name can not be empty");
			return;	
		case 7:	
			MessageDialog.openError(null, "Error", "Contract number can not be empty");
			return;	
		case 9:	
			MessageDialog.openError(null, "Error", "Type can not be empty");
			return;	
		}
		doSaveServiceCard();
		setDirty(false);
	}
	
	@Override
	public void doSaveAs() {
		// Do the Save As operation
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);
		setPartName("Service card");
		setTitleToolTip("Service Card Editor");
	}

	private boolean isDirty;

	public void setDirty(boolean isDirty) {
		this.isDirty = isDirty;
	}
	
	@Override
	public boolean isDirty() {
		return isDirty;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}
	
	
	public class ServiceCardContentProvider implements IStructuredContentProvider {

		public Object[] getElements(Object inputElement) {
			return inputList.toArray(new ServiceCardBean[0]);
		}

		public void dispose() {
		}

		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		}
		
	}


	public void focusGained(FocusEvent e) {
		int index = focusCellManager.getFocusCell().getColumnIndex();
		switch (index) {
		case 1:
			browseButton.setEnabled(true);
			break;
		case 2:
			tableViewer.getTable().setFocus();
			break;
		case 5:
			browseButton.setEnabled(true);
			((Text)editors[5].getControl()).setToolTipText("You can type or press F5 to select the Customer code");
			break;
		case 7:
			browseButton.setEnabled(true);
			((Text)editors[7].getControl()).setToolTipText("You can type or press F5 to select the Contract number");
			break;	
		case 9:
			browseButton.setEnabled(true);
			break;
		default:
			browseButton.setEnabled(false);
			break;
		}
	}


	public void focusLost(FocusEvent e) {
		int index = focusCellManager.getFocusCell().getColumnIndex();
//		switch (index) {
//		case 1:
////			browseButton.setEnabled(false);
//			break;
//		case 5:
//			browseButton.setEnabled(false);
//			break;
//		case 7:
//			browseButton.setEnabled(false);
//			break;
//		case 9:
//			browseButton.setEnabled(false);
//			break;	
//		default:
//			break;
//		}
	}


	public ArrayList<ServiceCardBean> getUpdateList() {
		return updateList;
	}


	public void setUpdateList(ArrayList<ServiceCardBean> updateList) {
		this.updateList = updateList;
	}

}
